import { Select } from 'antd'
import { useStore } from '@/store'

import { useState, useEffect } from 'react'


function SelectOption(props){
    const {item, selectValue, setSelectValue} = props
    const { operateStore } = useStore()
    const [ selectData, setSelectData] = useState()

    useEffect(() => {
        async function fetchList() {
            const params = {
                page: 0,
                pagesize: 9999
            }
            const data = await operateStore.getItems(item.form.api, params)
            data.list.map(d => {
                d["label"] = d[item.form.label]
                d["value"] = d[item.form.value]
                return d
            })
            setSelectData(data.list)
        }
        if(item.form.api === undefined){
            const data = item.form.data
            setSelectData(data)
        }else{
            fetchList()
        }
    }, [operateStore, item.form.api, item.form.label, item.form.value])

    function onChange(value) {
        if(selectValue !== undefined){
            const joinValue = {
                ...selectValue,
                ...{[item.name]: value}
            }
            setSelectValue(
                joinValue
            )
        }else{
            setSelectValue({[item.name]: value})
        }
    }

    return(
        <Select 
            showSearch
            value={selectValue ? selectValue[item.name]: ""}
            style={item.form.style} 
            placeholder = {item.form.placeholder}
            options = {selectData}
            onChange={onChange}
        >   
        </Select>

    )
} 

export default SelectOption 
